import React, { useState, useEffect } from 'react';
import { Container, Row, Col, Alert, Modal, Form, Button } from 'react-bootstrap';
import TodoList from './TodoList';
import TodoForm from './TodoForm';
import TodoService from '../services/TodoService';

const TodoApp = () => {
  const [todos, setTodos] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [showEditModal, setShowEditModal] = useState(false);
  const [editingTodo, setEditingTodo] = useState(null);
  const [editForm, setEditForm] = useState({
    name: '',
    category: '',
    complete: false
  });

  useEffect(() => {
    fetchTodos();
  }, []);

  const fetchTodos = async () => {
    try {
      setLoading(true);
      const response = await TodoService.getAllTodos();
      console.log('API响应数据:', response);  // 添加日志记录
      
      if (response.data && response.data.data) {
        const todoData = response.data.data || [];
        console.log('待办事项数据:', todoData);  // 添加日志记录
        setTodos(todoData);
      } else {
        console.error('API返回的数据格式不符合预期:', response);
        setError('获取任务列表失败，API返回格式不符合预期');
      }
    } catch (err) {
      setError('获取任务列表失败，请稍后再试');
      console.error('Error fetching todos:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleAddTodo = async (todo) => {
    try {
      console.log('添加任务:', todo);  // 记录要添加的任务数据
      const response = await TodoService.createTodo(todo);
      console.log('添加任务响应:', response);  // 记录API响应
      
      if (response.data.code === 200) {
        setTodos([...todos, response.data.data]);
      } else {
        setError('添加任务失败：' + response.data.message);
      }
    } catch (err) {
      setError('添加任务失败，请稍后再试');
      console.error('Error adding todo:', err);
    }
  };

  const handleUpdateTodo = async (id, updatedTodo) => {
    try {
      console.log('更新任务:', id, updatedTodo);  // 记录要更新的任务数据
      const response = await TodoService.updateTodo(id, updatedTodo);
      console.log('更新任务响应:', response);  // 记录API响应
      
      if (response.data.code === 200) {
        setTodos(
          todos.map((todo) => (todo.id === id ? { ...todo, ...updatedTodo } : todo))
        );
      } else {
        setError('更新任务失败：' + response.data.message);
      }
    } catch (err) {
      setError('更新任务失败，请稍后再试');
      console.error('Error updating todo:', err);
    }
  };

  const handleToggleComplete = async (id) => {
    const todo = todos.find(t => t.id === id);
    if (todo) {
      await handleUpdateTodo(id, { complete: !todo.complete });
    }
  };

  const handleDeleteTodo = async (id) => {
    try {
      const response = await TodoService.deleteTodo(id);
      if (response.data.code === 200) {
        // 从列表中移除已删除的待办事项
        setTodos(todos.filter(todo => todo.id !== id));
        setError(null);
      } else {
        setError('删除任务失败：' + response.data.message);
      }
    } catch (err) {
      setError('删除任务失败，请稍后再试');
      console.error('Error deleting todo:', err);
    }
  };

  // 打开编辑模态框
  const handleEditTodo = (todo) => {
    setEditingTodo(todo);
    setEditForm({
      name: todo.name,
      category: todo.category || '',
      complete: todo.complete
    });
    setShowEditModal(true);
  };

  // 处理编辑表单字段变化
  const handleEditFormChange = (e) => {
    const { name, value, checked } = e.target;
    setEditForm({
      ...editForm,
      [name]: name === 'complete' ? checked : value
    });
  };

  // 保存编辑的任务
  const handleSaveEdit = async () => {
    if (!editingTodo) return;
    
    try {
      await handleUpdateTodo(editingTodo.id, editForm);
      setShowEditModal(false);
      setEditingTodo(null);
    } catch (err) {
      console.error('Error saving todo edit:', err);
    }
  };

  return (
    <Container className="py-4">
      <Row className="mb-4">
        <Col>
          <h1 className="text-center">我的待办事项</h1>
        </Col>
      </Row>
      
      {error && (
        <Row className="mb-3">
          <Col>
            <Alert variant="danger">{error}</Alert>
          </Col>
        </Row>
      )}
      
      <Row className="mb-4">
        <Col md={12} className="task-container">
          <TodoForm onAddTodo={handleAddTodo} />
        </Col>
      </Row>
      
      <Row>
        <Col md={12} className="task-container">
          {loading ? (
            <div className="text-center p-5">
              <div className="spinner-border text-primary" role="status">
                <span className="visually-hidden">加载中...</span>
              </div>
              <p className="mt-2">正在加载任务...</p>
            </div>
          ) : (
            <TodoList 
              todos={todos} 
              onToggleComplete={handleToggleComplete}
              onDeleteTodo={handleDeleteTodo}
              onEditTodo={handleEditTodo}
            />
          )}
        </Col>
      </Row>

      {/* 编辑任务模态框 */}
      <Modal show={showEditModal} onHide={() => setShowEditModal(false)}>
        <Modal.Header closeButton>
          <Modal.Title>编辑任务</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <Form>
            <Form.Group className="mb-3" controlId="editTodoName">
              <Form.Label>任务名称</Form.Label>
              <Form.Control
                type="text"
                name="name"
                value={editForm.name}
                onChange={handleEditFormChange}
                required
              />
            </Form.Group>

            <Form.Group className="mb-3" controlId="editTodoCategory">
              <Form.Label>任务分类</Form.Label>
              <Form.Control
                type="text"
                name="category"
                value={editForm.category}
                onChange={handleEditFormChange}
              />
            </Form.Group>

            <Form.Group className="mb-3" controlId="editTodoComplete">
              <Form.Check
                type="switch"
                label="标记为已完成"
                name="complete"
                checked={editForm.complete}
                onChange={handleEditFormChange}
              />
            </Form.Group>
          </Form>
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={() => setShowEditModal(false)}>
            取消
          </Button>
          <Button variant="primary" onClick={handleSaveEdit}>
            保存
          </Button>
        </Modal.Footer>
      </Modal>
    </Container>
  );
};

export default TodoApp; 